package com.xiaobai.im.server.entity;

import com.xiaobai.im.server.common.Constants;
import io.netty.buffer.ByteBuf;
import lombok.Data;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

@Data
public class Message {
    /**
     * 魔法数
     */
    private int magicNum;

    /**
     * 版本
     */
    private short version;

    /**
     * 消息类型，心跳/消息
     */
    private short type;

    /**
     * 来源用户id
     */
    private long from;

    /**
     * 前往用户id
     */
    private long to;

    /**
     * 当前消息序号
     */
    private short number;

    /**
     * 消息类型，文本/图片
     */
    private short dataType;

    /**
     * 消息长度
     */
    private int length;

    /**
     * 消息体
     */
    private String data;

    public static Message buildMessageAndVerify(ByteBuf byteBuf) {
        Message message = new Message();
        message.magicNum = byteBuf.readInt();
        /*if (message.magicNum != Constants.MAGIC_NUM) {
            throw new IllegalArgumentException("消息不符合格式");
        }*/
        message.version = byteBuf.readShort();
        message.type = byteBuf.readShort();
        message.length = byteBuf.readInt();
        message.from = byteBuf.readLong();
        message.to = byteBuf.readLong();
        message.number = byteBuf.readShort();
        message.dataType = byteBuf.readShort();
        message.data = byteBuf.toString(Charset.defaultCharset());
        return message;
    }
}
